package com.woniuxy.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    /**
    /**
     * 订单添加接口：需要保证接口的幂等性
     * 实现方案1：Redis分布式锁实现
     */
    @PostMapping("add")
    public String submitOrder(String orderNumber){
        if (redisTemplate.hasKey("order_"+ orderNumber)){
            return "数据已处理，请勿重复提交";
        }
        //保存锁redis,
        redisTemplate.opsForValue().set("order_"+ orderNumber,"", Duration.ofSeconds(5));
        System.out.println("订单生成成功！" + orderNumber);
        return "ok";
    }

    /**
     * 方案2（推荐）
     *redisson实现幂等
     */
    @PostMapping("add2")
    public String submitOrder2(String orderNum) {
        String key = "order_" + orderNum;
        // 获取分布式锁对象RLock
        RLock rLock = redissonClient.getLock(key);
        try {
            // 加锁；默认锁的过期时间是30秒；
            // 后台会启动一个看门狗的线程watchdog，每10秒执行一次，给锁进行续期到30秒
            rLock.lock();
            // 执行加锁的业务操作....
            Thread.sleep(50 * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            rLock.unlock();
        }
        return "ok";
    }
}
